﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
//using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
//using System.Xml.Linq;
using System.Globalization;


public partial class ODetils : System.Web.UI.Page
{
    DataSet ds = null;//fill products
    DataSet dst = null;//fill state
    DataSet dsc = null;// fill counties
    rUser user;
    public static RE_GenericBean[] photorb;
  
    public static int orden;
    static int detail;
    static int desplego; // si desplego ya el fee
    public static RE_GenericBean objeto=null;
     int agentcorrelativo = 1;
    static Table tabla = null;
    static Table tablephoto = new Table();
    static TableRow row;
    static int  TableSize;
    static int product_id = 0;
    static RE_GenericBean[] views;
    static DataSet dsphotos;
    static RE_GenericBean rgCount;
    protected void Page_Load(object sender, EventArgs e)
    {


      
            if (Session["size"] == null) { Session["size"] = 0; }
            if (Session["userid"] == null)

            {

                Response.Redirect("../Default.aspx");
            }
            else
            {

                if (!Page.IsPostBack)
                {
                    tablephoto.Controls.Clear();
                    tablephoto.CellPadding = 0;
                    tablephoto.BorderColor = System.Drawing.Color.LightGray;
                    tablephoto.BorderWidth= 1;
                    

                    TableSize = 0;
                    row = new TableRow();
                    tablephoto.Rows.Add(row);
                    user = (rUser)Session["userid"];
                    if (Request.QueryString["id"] != "")
                    {

                        try
                        {
                            orden = int.Parse(Request.QueryString["id"].ToString());

                            TabContainer1.ActiveTab = TabPanel1;
                            fillproducts();
                            fillstates();

                            RE_GenericBean rgb = DB.getOrden(orden);
                            photorb = new RE_GenericBean[100];
                          
                            
                            if (rgb != null)
                            {
                                getDataOrderOwner(rgb.strC22.ToString());
                                torder.Text = rgb.intC1.ToString();
                                jobtype.Text = rgb.strC1.ToString();

                                CultureInfo ci = new CultureInfo("en-US");
                                tduedate.Text = DateTime.Parse(rgb.strC2.ToString(), ci).Date.ToShortDateString();
                                torderdate.Text = DateTime.Parse(rgb.strC11.ToString()).Date.ToShortDateString();
                                tordertime.Text = DateTime.Parse(rgb.strC12.ToString()).Hour.ToString() + ":" + DateTime.Parse(rgb.strC12.ToString()).Minute.ToString();

                                RE_GenericBean duetimege = Utility.Hora24horastoFormatoAMPM(rgb.strC3.ToString());
                                duetimeampm.Text = duetimege.strC2;
                                duetime.Text = duetimege.strC1;
                                //llenando companias
                                fillcompanies(rgb);
                                //llenando cuentas
                                fillaccounts(rgb);
                                fillstatus(rgb);
                                rgCount = rgb;
                                
                                
                                

                                if (rgb.strC4.ToString().Equals("")) { comments.Text = "None"; } else { comments.Text = rgb.strC4.ToString(); }

                                tstnumber.Text = rgb.strC5.ToString();
                                tstaddress.Text = Utility.toCapital(rgb.strC6.ToString());
                                tcity.Text = Utility.toCapital(rgb.strC7.ToString());
                                state.Text = Utility.toCapital(rgb.strC8.ToString());

                                //llenando estados
                                cbstatus.Text = rgb.strC10.ToString().ToUpper();
                                fillcounties(state.Text, rgb);

                                Address.Text = rgb.strC5.ToString() + " " + rgb.strC6.ToString() + "  " + rgb.strC7.ToString() + " , " + DB.getStateInitial(rgb.strC8.ToString()) ; 

                                tzip.Text = rgb.strC9.ToString();
                                string a1 =  Utility.toCapital(rgb.strC18.ToString());
                                county.Text =a1;
                                tpstnum.Text = rgb.strC13.ToString();
                                tpstadd.Text = rgb.strC14.ToString();
                                tpzip.Text = rgb.strC17.ToString();
                                cbOPState.Text = rgb.strC16.ToString();
                                duetimeampm.Text = rgb.strC19.ToString();
                                attributes.Text = Utility.toCapital(rgb.strC24);
                                
                                tfee.Text = Utility.formatNumber(double.Parse(rgb.strC20));
                                if ((long.Parse(user.getPermiso()) & 16) == 16)
                                {
                                    double pro = double.Parse(rgb.strC20.ToString()) - double.Parse(rgb.strC21.ToString());
                                    profit.Text = Utility.formatNumber(pro);
                                    tcheck.Text = "";
                                }

                                if ((long.Parse(user.getPermiso()) & 1) == 1)
                                {

                                    editbutton.Visible = true;
                                    ImageButton8.Visible = true;
                                    PFailAdd.Visible = true;
                                    crearTablaProcess(DB.getProductId(jobtype.Text));
                                    PFailDetail.Enabled = true;
                                   
                                    saveclosephoto.Visible = true;
                                    savesubmit.Visible = true;
                                    saveclose.Visible = true;
                                    upload.Visible = true;
                                }
                                else
                                {
                                    saveclosephoto.Visible = false; editbutton.Visible = false; savesubmit.Visible = false;
                                    PFailDetail.Enabled = false;
                                }



                                if (DB.hasOptional(jobtype.SelectedValue) == 1)
                                {

                                    Panel1.Visible = true;
                                }


                                DataSet dsf = DB.getFail(orden);
                                if (dsf != null)
                                {
                                    gv_fail.DataSource = dsf;
                                    gv_fail.DataBind();
                                }
                                DropDownList3_SelectedIndexChanged(null,null);

                                tablephoto.Width = 1000;
                                string type = DB.getProductType(jobtype.Text);
                                int loadphotos = 0;
                                PExPho1.Visible = false;
                                PExPho2.Visible = false;
                                PAppInfo.Visible = false;
                                PnlCallRecords.Visible = false;
                                if (type.ToUpper().Equals("EXT"))
                                {
                                    
                                    cargarEXT();
                                    loadphotos = 1;



                                   
                                }
                                if (type.ToUpper().Equals("INT"))
                                {
                                    cargarINT();
                                    loadphotos = 1;
                                    PExPho1.Visible = true;
                                    PExPho2.Visible = true;
                                    PAppInfo.Visible = true;
                                    PnlCallRecords.Visible  = true;

                                    
                                }
                                if (type.ToUpper().Equals("EXTREP"))
                                {
                                    cargarEXTREP();
                                    loadphotos = 1;
                                 
                                  
                                }
                                if (type.ToUpper().Equals("INTREP"))
                                {
                                    cargarINTREP();
                                    loadphotos = 1;
                                    PExPho1.Visible = true;
                                    PExPho2.Visible = true;
                                    PAppInfo.Visible = true;
                                    PnlCallRecords.Visible = true;
                                   
                                }
                                if (type.ToUpper().Equals("REKEY")){
                                    PAppInfo.Visible = true;
                                }
                                
                                if (loadphotos==1){
                                    getDataOrderOwner(rgb.strC22.ToString());
                                    loadPhotos();
                                  
                                    //pedirWS XM email client
                                   
                                    getUploadBy();
                                }
                                



                            }
                        }
                        catch (Exception ee) { }
                    }
                    else { }
                }
                else
                {
                    product_id = DB.getProductId(jobtype.Text);
                    crearTablaProcess(product_id);
                    if (detail == 1) { PFailDetail.Visible = true; }
                     PBoxPhoto.Controls.Add(tablephoto);

                }

            }
       
    }

    private void fillcompanies(RE_GenericBean rg)
    {
        //llenando cb company
        try
        {
            RE_GenericBean rgb = rg;
            string rxmlcompanies = null;
            com.bpophotos.www.Service service = new com.bpophotos.www.Service();
            rxmlcompanies = service.getCompanies();
            if (!rxmlcompanies.Equals("") || rxmlcompanies != null)
            {
                DataSet dsc = Utility.getCompanies(rxmlcompanies);
                ListItem listitem0 = new ListItem();
                listitem0.Text = "Select One"; listitem0.Value = "";
                company.Items.Add(listitem0);

                for (int ii = 0; ii <= (dsc.Tables[0].Rows.Count - 1); ii++)
                {
                    ListItem listitem = new ListItem();
                    listitem.Text = dsc.Tables[0].Rows[ii][1].ToString();
                    listitem.Value = dsc.Tables[0].Rows[ii][0].ToString();
                    company.Items.Add(listitem);

                    if (dsc.Tables[0].Rows[ii][0].ToString() == rgb.strC23.ToString())
                    {
                        company.SelectedValue = listitem.Value;
                    }
                }

            }

        }
        catch (Exception ec)
        {
            Utility.writeError("WS getCompanies no devolvio companias " + ec.Message);

        }

    }



    private void loadPhotos()
    {//trae todas las fotos de la orden, y las pones en cuadros

        dsphotos = DB.getPhotosOrden(orden);
        if (dsphotos!=null){
            if (dsphotos.Tables[0].Rows.Count!=0)
            {
                 for (int i = 0; i < dsphotos.Tables[0].Rows.Count; i++ )
                    {
                         photorb[i] = new RE_GenericBean();
                         photorb[i].strC1 = dsphotos.Tables[0].Rows[i][3].ToString();//path
                         photorb[i].intC2 = int.Parse(dsphotos.Tables[0].Rows[i][1].ToString());//viewid
                         photorb[i].intC3 = int.Parse(dsphotos.Tables[0].Rows[i][2].ToString());//num
                         photorb[i].strC2 = dsphotos.Tables[0].Rows[i][4].ToString();//comm
                         photorb[i].intC4 = 1;//indica si viene de la base de datos
                         TableSize++;
                         addoldcell(TableSize, jobtype.Text,photorb[i].intC2, photorb[i].strC1, photorb[i].strC2) ;
                         if (TableSize == 1)
                         {
                             ((Image)TabPanel2.FindControl("PhotoMain")).ImageUrl = "~/data/photos/" + photorb[i].strC1;

                         }

            }
                 //lleno renglon si son menos de 4 fotos los que tiene la orden
                 if (dsphotos.Tables[0].Rows.Count <4) {
                     int faltan = 4- dsphotos.Tables[0].Rows.Count;
                     for (int ii = 0; ii < faltan; ii++ ) {
                         TableSize++;
                         addnewcell(TableSize, jobtype.Text, -1);
                     }
                 
                 }
        }else{
                //si no tiene ninguna genero un row
            for (int j = 0; j < 4; j++ ) {

                TableSize++;
                addnewcell(TableSize, jobtype.Text, -1);
            }
                
            }
        }
        PBoxPhoto.Controls.Add(tablephoto);
        }

    private void addoldcell(int TableSize, string strjobtype, int viewid, string path, string comments)
    {
        if (TableSize == 1)
        {
            row = new TableRow();
            tablephoto.Rows.Add(row);
        }

        if ((TableSize % 4)==0)
        {
          

            row.Cells.Add(oldBox(TableSize, strjobtype, viewid, path, comments));
            tablephoto.Rows.Add(row);
            row = new TableRow();

        }
        else
        {
            row.Cells.Add(oldBox(TableSize, strjobtype, viewid, path, comments));
            tablephoto.Rows.Remove(row);
            tablephoto.Rows.Add(row);

        }
    }


    private void addnewcell(int TableSize, string strjobtype, int viewid)
    {
       
       
        if (TableSize == 1)
        {
            row = new TableRow();
            tablephoto.Rows.Add(row);
        }

         
        if ((TableSize%4)==0)
        {
            
            row.Cells.Add(newBox(TableSize, strjobtype, viewid));
            tablephoto.Rows.Add(row);
            row = new TableRow();

        }
        else
        {
            row.Cells.Add(newBox(TableSize, strjobtype, viewid));
            tablephoto.Rows.Remove(row);
            tablephoto.Rows.Add(row);


            

        }
    }
    

private void getUploadBy()
{
    /////////weeeebbbSERvice
    string rxml = "";
   com.bpophotos.www.Service service = new com.bpophotos.www.Service();
    rxml= service.UsuariosPorPerfil(4);

    /*if (rxml == "")
    {
       rxml = "<lista_usuarios><respuestaID>1</respuestaID><datos_registro><user>Juanito</user><name>Juan</name><lastname>Perez</lastname><comp-name>ABcompany</comp-name><alias>AB</alias><email>astrid.bolanos@gmail.com</email></datos_registro>";
        rxml = rxml + "<datos_registro><user>PedroG</user><name>Pedro</name><lastname>Gonzalez</lastname><comp-name>KYCompany</comp-name><alias>PG</alias><email>pe.k@gmail.com</email></datos_registro>";
        rxml = rxml + "<datos_registro><user>OlgaM</user><name>Olga</name><lastname>Mendez</lastname><comp-name>RoboCompany</comp-name><alias>OM</alias><email>olga123@gmail.com</email></datos_registro>";
        rxml = rxml + "</lista_usuarios>";
    }*/
    if (!rxml.Equals("")|| rxml!=null){ 
    DataSet dsuploadby = Utility.getUsuariosporPerfil(rxml);
    ListItem listitem0 = new ListItem();
    listitem0.Text = "Select One"; listitem0.Value = "";
    cbuploadby.Items.Add(listitem0);
   
    
    for (int ii = 0; ii <= (dsuploadby.Tables[0].Rows.Count - 1); ii++)
    {
        ListItem listitem = new ListItem();
        listitem.Text = dsuploadby.Tables[0].Rows[ii][4].ToString() + "- " + dsuploadby.Tables[0].Rows[ii][1].ToString() + " " + dsuploadby.Tables[0].Rows[ii][2].ToString(); listitem.Value = dsuploadby.Tables[0].Rows[ii][4].ToString(); 
        cbuploadby.Items.Add(listitem);

    }
    }
    RE_GenericBean vendor = new RE_GenericBean();
    vendor = DB.getValueCampo("UPLOADBY", orden, "PHOTOS");
    if (vendor != null) { cbuploadby.SelectedValue = vendor.strC1;
    //timeupload.Text = Utility.getsrtTime(vendor.strC2);
    //dateupload.Text = Utility.getsrtDate(vendor.strC2);


    }else{
        cbuploadby.SelectedIndex=0;
    }
    RE_GenericBean rcv = DB.getValueCampo("RECEIVED", orden, "PHOTOS");
    if (rcv != null)   {   photosreceived.SelectedValue = rcv.strC1;}else { photosreceived.SelectedIndex=0;}
    RE_GenericBean completes = DB.getValueCampo("COMPLETEDSET", orden, "PHOTOS");
      if (completes != null)   {   completeset.SelectedValue = completes.strC1;}else { completeset.SelectedIndex=0;}
    RE_GenericBean exterior = DB.getValueCampo("EXTERIORONLY", orden, "PHOTOS");
      if (exterior != null)   {   typeonly.SelectedValue = exterior.strC1;}else { typeonly.SelectedIndex=0;}
    RE_GenericBean commentspho = DB.getValueCampo("COMMENTS", orden, "PHOTOS");
      if (commentspho != null)   {   commnetsphotos.Text = commentspho.strC1;}

    
    
    

}

private void getDataOrderOwner(string userID)
{
             //Consumir WSSSSS
           
    com.bpophotos.www.Service service = new com.bpophotos.www.Service();
    string datos= service.getDatosUsuario("ADMIN");
             
            /*String datos = "<?xml version=\"1.0\" encoding=\"utf-8\"?><datos_respuesta>  <respuestaid> 1</respuestaid>";
            datos = datos + "<usuarioid>23</usuarioid><nombre>astrid</nombre> <apellido>bolanos</apellido> <alias>lucianab</alias>";
            datos = datos + " <perfilid>admin</perfilid><permiso>1111111</permiso><imagen>.//data/logos//default.jpeg</imagen><email>astrid.bolanos@gmail.com</email></datos_respuesta>";*/
               
           if (datos!=null || datos!=""){
            rUser rreg = Utility.getRUser(datos);
            if (rreg != null)
            {
                if (rreg.getRespuestaId() == 1)
                {
                    emailowner.Text = rreg.getEmail();

                }
            }
           }
}
    private void cargarINTREP()
    {
        int product_id = DB.getProductId(jobtype.Text);
        DataSet view= DB.getProductView(product_id);
       productlist.DataSource = view;
        productlist.Items.Add("View list");
       for (int i = 0; i <= (view.Tables[0].Rows.Count - 1); i++)
        {
            string nameItem = view.Tables[0].Rows[i][0].ToString();
            productlist.Items.Add(nameItem);
       }
           
    }

    private void cargarEXTREP()
    {
        int product_id = DB.getProductId(jobtype.Text); 
        DataSet view= DB.getProductView(product_id);
         productlist.DataSource = view;
        productlist.Items.Add("View list");
       for (int i = 0; i <= (view.Tables[0].Rows.Count - 1); i++)
        {
            string nameItem = view.Tables[0].Rows[i][0].ToString();
            productlist.Items.Add(nameItem);
       }
    }

    private void cargarINT()
    {
        int product_id = DB.getProductId(jobtype.Text);
        DataSet view= DB.getProductView(product_id);
        productlist.DataSource = view;
        productlist.Items.Add("View list");
       for (int i = 0; i <= (view.Tables[0].Rows.Count - 1); i++)
        {
            string nameItem = view.Tables[0].Rows[i][0].ToString();
            productlist.Items.Add(nameItem);
       }
    }

    private void cargarEXT()
    {

        int product_id = DB.getProductId(jobtype.Text);
        DataSet view= DB.getProductView(product_id);
       productlist.DataSource = view;
        productlist.Items.Add("View list");
       for (int i = 0; i <= (view.Tables[0].Rows.Count - 1); i++)
        {
            string nameItem = view.Tables[0].Rows[i][0].ToString();
            productlist.Items.Add(nameItem);
       }

       
    }

    private void addnewRowTablePhotos(int viewid)
    {
              
            row = new TableRow();
            TableCell cell;

            for (int i = 1; i < 5; i++)
            {
                cell = new TableCell();

              cell.Controls.Add(newBox(TableSize + 1, jobtype.Text, viewid));
                 row.Cells.Add(cell);
                TableSize++;


            }

           tablephoto.Rows.Add(row);
            PBoxPhoto.Controls.Add(tablephoto);
            
        
        
        
        }

    private void crearTablaProcess(int product_id)
    {


        tabla = new Table();
        tabla.CellPadding = 0;
        tabla.CellSpacing = 0;
        

        TableRow rowheader = new TableRow();
        rowheader.BackColor = System.Drawing.Color.FromName("#9AC9F8");
        rowheader.CssClass = "letraNegra14";
        TableCell cellheader = new TableCell();
        cellheader.Text = "Product";
        cellheader.HorizontalAlign = HorizontalAlign.Left;
        rowheader.Cells.Add(cellheader);
        TableCell cellheader1 = new TableCell();
        cellheader1.Text = "Agent";
        cellheader1.HorizontalAlign = HorizontalAlign.Left;
        rowheader.Cells.Add(cellheader1);
        TableCell cellheader2 = new TableCell();
        cellheader2.Text = "Fee";
        rowheader.Cells.Add(cellheader2);
        TableCell cellheader3 = new TableCell();
        cellheader3.Text = "Completed";
        rowheader.Cells.Add(cellheader3);
        TableCell cellheader4 = new TableCell();
        cellheader4.Text = "Date";
        cellheader4.HorizontalAlign = HorizontalAlign.Left;
        rowheader.Cells.Add(cellheader4);
        TableCell cellheader5 = new TableCell();
        cellheader5.Text = "Time";
        cellheader4.HorizontalAlign = HorizontalAlign.Left;
        rowheader.Cells.Add(cellheader5);
        tabla.Rows.Add(rowheader);

        DataSet process = DB.getProcessProduct(product_id);
        if (process != null)
        {
            for (int i = 0; i <= (process.Tables[0].Rows.Count - 1); i++)
            {

                TableRow row = new TableRow();
                row.CssClass = "letraNegra13";


                TableCell cellprocess = new TableCell();
                cellprocess.Text = process.Tables[0].Rows[i][0].ToString();
                cellprocess.Width = 150;
                cellprocess.HorizontalAlign = HorizontalAlign.Left;
                row.Cells.Add(cellprocess);


                DropDownList combo = new DropDownList();
                combo.ID = "agent" + agentcorrelativo;
                ListItem listitemvacio = new ListItem();
                listitemvacio.Text = "No"; listitemvacio.Value = "No";
                combo.Items.Add(listitemvacio);



                int processperfil = int.Parse(process.Tables[0].Rows[i][1].ToString());

               
                string rxml = null;
                try
                {
                    com.bpophotos.www.Service service = new com.bpophotos.www.Service();
                    rxml = service.UsuariosPorPerfil(processperfil);
                }catch (Exception e){}
                /*string rxml = "<lista_usuarios><respuestaID>1</respuestaID><datos_registro><user>Juanito</user><name>Juan</name><lastname>Perez</lastname><comp-name>ABcompany</comp-name><alias>AB</alias><email>astrid.bolanos@gmail.com</email></datos_registro>";
                rxml = rxml + "<datos_registro><user>PedroG</user><name>Pedro</name><lastname>Gonzalez</lastname><comp-name>KYCompany</comp-name><alias>PG</alias><email>pe.k@gmail.com</email></datos_registro>";
                rxml = rxml + "<datos_registro><user>OlgaM</user><name>Olga</name><lastname>Mendez</lastname><comp-name>RoboCompany</comp-name><alias>OM</alias><email>olga123@gmail.com</email></datos_registro>";
                rxml = rxml + "</lista_usuarios>";*/
                if (rxml!=null || rxml!=""){
                
                DataSet usuariosperfil = Utility.getUsuariosporPerfil(rxml);
                if (usuariosperfil != null)
                {
                    for (int ii = 0; ii <= (usuariosperfil.Tables[0].Rows.Count - 1); ii++)
                    {
                        ListItem listitem = new ListItem();
                        string nombrecompleto= usuariosperfil.Tables[0].Rows[ii][1].ToString() + " " + usuariosperfil.Tables[0].Rows[ii][2].ToString(); listitem.Value = usuariosperfil.Tables[0].Rows[ii][4].ToString();
                        listitem.Text = usuariosperfil.Tables[0].Rows[ii][4].ToString() + "- " + Utility.toCapital(nombrecompleto) ;
                        combo.Items.Add(listitem);

                        string dsuser = usuariosperfil.Tables[0].Rows[ii][4].ToString();
                        RE_GenericBean vendor = new RE_GenericBean();
                        vendor = DB.getValueCampo("VENDOR", orden, process.Tables[0].Rows[i][0].ToString());
                        if (vendor != null)
                        {
                            if (dsuser.ToUpper().Equals(vendor.strC1))
                            {

                                combo.SelectedValue = usuariosperfil.Tables[0].Rows[ii][4].ToString();


                            }
                        }

                    }//for usuariosperfil
                }
                }
                TableCell cellagent = new TableCell();
                cellagent.Width = 180;
                combo.Width = 170;
                cellagent.HorizontalAlign = HorizontalAlign.Left;
                cellagent.Controls.Add(combo);
                row.Cells.Add(cellagent);

                TableCell cellfee = new TableCell();
                if (desplego == 0)
                {
                    double fee = product.findClientFee(jobtype.Text);
                    
                    cellfee.Text = Utility.formatNumber(fee);//fee
                    desplego = 1;
                }
                else
                {

                    cellfee.Text = "";//fee
                }
                cellfee.Width = 50;

                row.Cells.Add(cellfee);

                //DONE
                TableCell celldone = new TableCell();
                TableCell celldate = new TableCell();
                TableCell celltime = new TableCell();
                celldone.Width = 80;
                celldate.Width = 100;
                celltime.Width = 80;
                RE_GenericBean done = new RE_GenericBean();
                done = DB.getValueCampo("DONE", orden, process.Tables[0].Rows[i][0].ToString());
                DropDownList cbdone = new DropDownList();
                cbdone.ID = "cbdone" + agentcorrelativo;
                cbdone.Width = 70;
                agentcorrelativo++;
                ListItem li = new ListItem();
                li.Text = "No"; li.Value = "No";
                cbdone.Items.Add(li);
                ListItem liy = new ListItem();
                liy.Text = "Yes"; liy.Value = "Yes";
                cbdone.Items.Add(liy);

                if (done == null) { cbdone.SelectedValue = "No"; celldate.Text = ""; }
                else
                { cbdone.SelectedValue = "Yes"; 
                    celldate.Text = DateTime.Parse(done.strC2).ToShortDateString(); celltime.Text = DateTime.Parse(done.strC2).ToShortTimeString(); 
                }
                celldone.Controls.Add(cbdone);
                row.Cells.Add(celldone);
                row.Cells.Add(celldate);
                row.Cells.Add(celltime);





                tabla.Rows.Add(row);
            }
            Pprocess.Controls.Add(tabla);


        }
    }

        
        

    
    private void fillproducts()
    {
        string nameItem;
        ds = DB.GetProducts();
        if (ds!=null){
        jobtype.Items.Add("Select One");
        for (int i = 0; i <= (ds.Tables[0].Rows.Count - 1); i++)
        {
            nameItem = ds.Tables[0].Rows[i]["name"].ToString();
            jobtype.Items.Add(nameItem);

        }
        }
    }

    private void fillstates()
    {

        dst = DB.GetStates();
        state.Items.Add("Select One");
        cbOPState.Items.Add("Select One");
        for (int i = 0; i <= (dst.Tables[0].Rows.Count - 1); i++)
        {
           
           
            if (dst.Tables[0].Rows[i]["enable"].ToString().Equals("1"))
            {
                string nameItem =Utility.toCapital(dst.Tables[0].Rows[i]["name"].ToString());
                state.Items.Add(nameItem);
                cbOPState.Items.Add(nameItem);
            }
        }


    }




    private void fillcounties(string state, RE_GenericBean rg)
    {
        RE_GenericBean rg2 = rg;
        string nameItem;
        dsc = DB.GetCounties(state);
        county.Enabled = true;
        if (dsc != null)
        {

            if (dsc.Tables[0].Rows.Count > 0)
            {
                county.Items.Add("Select One");
                for (int i = 0; i <= (dsc.Tables[0].Rows.Count - 1); i++)
                {


                    if (dsc.Tables[0].Rows[i]["enable"].ToString().Equals("1"))
                    {
                        nameItem = Utility.toCapital(dsc.Tables[0].Rows[i]["name"].ToString());
                        county.Items.Add(nameItem);
                        ListItem list = new ListItem();
                        list.Text = nameItem;
                        list.Value = dsc.Tables[0].Rows[i]["county"].ToString();
                        string a1 = dsc.Tables[0].Rows[i]["name"].ToString();
                        string a2 = rg2.strC18.ToString();
                        if (nameItem == Utility.toCapital(rg2.strC18.ToString()))
                        {
                            county.SelectedValue = list.Value;
                        }
                    }

                }
            }
            else
            {
                county.Enabled = false;
            }
        }

    }



    protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
    protected void fillcounties_SelectedIndexChanged(object sender, EventArgs e)
    {
        fillcounties(jobtype.SelectedItem.ToString(), rgCount);
    }

   
    protected void r(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        { 
            e.Row.Cells[0].Width=180;
            e.Row.Cells[0].Text = "REASON";
            e.Row.Cells[1].Width = 120;
            e.Row.Cells[1].Text = "DATE";
            e.Row.Cells[2].Width = 150;
            e.Row.Cells[2].Text = "AGENT REASSIGN";
            e.Row.Cells[3].Width = 150;
            e.Row.Cells[3].Text = "RESPONSABLE";
        }
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Cells[0].Width = 250;
            e.Row.Cells[1].Width = 250;
        }
    }

    

    protected void DropDownList3_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (cbfailed.Text == "Yes")
        {
            cbreason.Enabled = true;
            cbreason.Visible = true;
            cbagentreassign.Enabled = true;
            cbagentreassign.Visible = true;
           // cbreason_SelectedIndexChanged(null,null );


        }
        else {
            cbreason.Enabled = false;
            cbreason.Visible = false;
            cbagentreassign.Enabled = false;
            cbagentreassign.Visible = false;
        }
    }
    protected void cbreason_SelectedIndexChanged(object sender, EventArgs e)
    {
        //pedir a xml segun la opcion elegidda, los usuarios que se pueden asignar
        //Service se= new Service
        int failperfil = getFailPerfil(cbreason.SelectedItem.ToString());
        com.bpophotos.www.Service service = new com.bpophotos.www.Service();
        string rxml= service.UsuariosPorPerfil(failperfil);
       
        
        
      
          
        if (rxml!=null || rxml!=""){
        DataSet usuariosperfil = Utility.getUsuariosporPerfil(rxml);
        fillagentreassign(usuariosperfil);
        }
        
    }

    private void fillagentreassign(DataSet usuarios)
    {
        cbagentreassign.Items.Clear();
        cbagentreassign.Visible = true;
        cbagentreassign.Enabled = true;
        cbagentreassign.Items.Add("Select One");
        for (int i = 0; i <= (usuarios.Tables[0].Rows.Count - 1); i++)
        {
            string nameItem = Utility.toCapital(usuarios.Tables[0].Rows[i]["alias"].ToString());
            cbagentreassign.Items.Add(nameItem);

        }
    }

    private int getFailPerfil(string reason)
    {
        int result=0;
        if (reason.ToUpper().Equals("AGENT REASSIGN"))
        {
            result = 3;
        }
        if (reason.ToUpper().Equals("CLIENT"))
        {
            result = 3;
        }
        if (reason.ToUpper().Equals("DRIVER"))
        {
            result = 2;
        }
        if (reason.ToUpper().Equals("QC DEPARTMENT"))
        {
            result = 6;
        }
        if (reason.ToUpper().Equals("AGENT REDO"))
        {
            result = 3;
        }

        return result;
    }
    protected void ImageButton4_Click(object sender, ImageClickEventArgs e)
    {
        if (detail == 0) { detail = 1; } else { detail = 0; }
        if (detail == 1) { PFailDetail.Visible = true; } else { PFailDetail.Visible = false;  }
       
    }
    protected void dataBoundProcess(object sender, GridViewRowEventArgs e)
    {
      
        if (e.Row.RowType == DataControlRowType.Header)
        {
          
            desplego = 0;
        }
        if (e.Row.RowType == DataControlRowType.DataRow)
        {

        
          //pedir a xml segun la opcion elegidda, los usuarios que se pueden asignar
        //Service se= new Service

           
            int processperfil = int.Parse(e.Row.Cells[2].Text);
            com.bpophotos.www.Service service = new com.bpophotos.www.Service();
            string rxml = service.UsuariosPorPerfil(processperfil);
         
           
        
        //llenar combobox
        /*
        string rxml = "<lista_usuarios><respuestaID>1</respuestaID><datos_registro><user>Juanito</user><name>Juan</name><lastname>Perez</lastname><comp-name>ABcompany</comp-name><alias>AB</alias><email>astrid.bolanos@gmail.com</email></datos_registro>";
        rxml = rxml + "<datos_registro><user>PedroG</user><name>Pedro</name><lastname>Gonzalez</lastname><comp-name>KYCompany</comp-name><alias>PG</alias><email>pe.k@gmail.com</email></datos_registro>";
        rxml= rxml+ "<datos_registro><user>OlgaM</user><name>Olga</name><lastname>Mendez</lastname><comp-name>RoboCompany</comp-name><alias>OM</alias><email>olga123@gmail.com</email></datos_registro>";
        rxml= rxml+"</lista_usuarios>";*/
      
        DataSet usuariosperfil = Utility.getUsuariosporPerfil(rxml);
       string shtml = "<select name=\"Agent_" + agentcorrelativo + "\" runat=\"server\"  onChange=\"writeprocess('" + e.Row.Cells[0].Text + "','Agent_" + agentcorrelativo + "'," + agentcorrelativo + ")\"><option value='' selected='selected'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</option>";
       
            agentcorrelativo++;
        for (int i = 0; i <= (usuariosperfil.Tables[0].Rows.Count - 1); i++)
        {
            shtml = shtml + "<option  value=" + usuariosperfil.Tables[0].Rows[i]["alias"].ToString() + ">" + usuariosperfil.Tables[0].Rows[i]["alias"].ToString() + "</option>";
        }
       e.Row.Cells[2].Text = shtml+ "</select>";
      
            //ir a traer precio de products
               
            if (desplego == 0)
            {
                double fee = product.findClientFee(jobtype.Text);
                e.Row.Cells[3].Text = Utility.formatNumber(fee);//fee
                desplego = 1;
            }
            else {

                e.Row.Cells[3].Text = "";//fee
            }


            //ir atraer a process_product info done y fecha si no tiene nada done=no, fecha=""
            RE_GenericBean rb = null;
            rb = DB.getValueCampo("DONE", orden, e.Row.Cells[1].Text);
            e.Row.Cells[4].Text = "<select name=done_" + agentcorrelativo + " width=\"100\" ><option value='' selected='selected'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</option><option>YES</option></select>";
            if (rb != null)
            {
               
                if (rb.strC1 != null) {// e.Row.Cells[3].Text = rb.strC1;
               
                }//done 
                if (rb.strC2 != null) { e.Row.Cells[5].Text = rb.strC2; }//date 

            }
            else {
                // e.Row.Cells[3].Text = "";
                 e.Row.Cells[5].Text = "";
            }

            
          

        }
    }
    protected void saveclose_Click(object sender, ImageClickEventArgs e)
    {
        //Guardar orden information
       int result= saveOrder();
        
        //Guardar Special Attributes

        result = result * saveSpecialAtt();
        //Guardar Process
        result= result * saveProcess();
        
       
       
    }
    protected void savesubmit_Click(object sender, ImageClickEventArgs e)
    {
        int result;
        //Guardar orden information
        result= saveOrder();


       
        //Guardar Special Attributes
        result= result * saveSpecialAtt();
        
        //Guardar Process
         result= result* saveProcess();
         //Verificar que ya tiene y darle completed
         submitOrder(orden);
        if (result == 0) {
           /* Response.Write("<" + "script language='javascript'>");
            Response.Write("alert('Please enter correct values.');");

            Response.Write("<" + "/script>");*/
        }
    }
    private int saveProcess()
    {
        int result = 0;
        for (int i = 1; i < tabla.Rows.Count ; i++ )
        {
            string processname; string campo; 
            campo = "VENDOR";
            AjaxControlToolkit.TabPanel panel = TabPanel1;
            string vendorvalue= ((DropDownList)panel.FindControl("agent"+i)).SelectedValue;
            string donevalue = ((DropDownList)panel.FindControl("cbdone" + i)).SelectedValue;
            processname = tabla.Rows[i].Cells[0].Text;
            if (!vendorvalue.ToUpper().Equals("NO")){
                int intCampo = DB.getCampoID(processname, "VENDOR");
                int cvendor = DB.saveOrderProcess(orden, intCampo, vendorvalue);
            }
            if (!donevalue.ToUpper().Equals("NO"))
            {
                int intCampo2 = DB.getCampoID(processname, "DONE");
                int cdone = DB.saveOrderProcess(orden, intCampo2, donevalue);
            }
           
           
        }

        return result;
    }

    private int saveSpecialAtt()
    {

            int result = DB.updateOrderAttibutes(orden,attributes.Text, appshe.Text, tfee.Text, tcheck.Text, paid.Text,asisValue.Text, repair.Text, efectivedate.Text );
            return result;
    }

    private int saveOrder()
    {
        string hora = Utility.HoraAMPMtoFormato24horas(duetime.Text, duetimeampm.Text );
       int result = DB.updateOrder(orden,torder.Text,jobtype.Text,cbstatus.Text, company.Text, account.Text, torderdate.Text, tordertime.Text, tduedate.Text, hora, tstnumber.Text, tstaddress.Text, tcity.Text, county.Text,  state.Text, tzip.Text , comments.Text);
       return result;
    }


    private int submitOrder( int order)
    {
        int result = 0;
        int sumYes = 0;
        int product_id = DB.getProductId(jobtype.Text);
        DataSet process = DB.getProcessProduct(product_id);
        if (process!=null){
        for (int i = 0; i <= (process.Tables[0].Rows.Count - 1); i++)
        {         string processname= process.Tables[0].Rows[i][0].ToString();
                  int intCampo = DB.getCampoID(processname, "DONE");
                  DataSet donestatus = DB.getDoneProduct(order, intCampo);
                 if(donestatus!=null){
                     if (!processname.Equals("SUBMITTED") )
                     {
                         if (donestatus.Tables[0].Rows[0][2]!=null) {
                         if (donestatus.Tables[0].Rows[0][2].ToString().ToUpper().Equals("YES"))
                         {
                             sumYes = sumYes + 1;
                         }
                         }
                     }
                 }
       
        }
            if (sumYes==(process.Tables[0].Rows.Count -1)){
                
                int statusid = DB.getStatusId("COMPLETED");
                DB.setStatusOrder(order, statusid);
            }


           

        }
        return result;
    }
    protected void editbutton_Click(object sender, ImageClickEventArgs e)
    {
        enableAll();
        saveclosephoto.Visible = true;
        saveclose.Visible = true;
        savesubmit.Visible = true;
    }

    private void enableAll()
    {
        torder.Enabled = true;
        jobtype.Enabled = true;
        company.Enabled = true;
        torderdate.Enabled = true;
        tstaddress.Enabled = true;
        tstnumber.Enabled = true;
        tzip.Enabled = true;
        account.Enabled = true;
        tduedate.Enabled = true;
        duetime.Enabled = true;
        duetimeampm.Enabled = true;
        tcheck.Enabled = true;
        tcity.Enabled = true;
        state.Enabled = true;
        comments.Enabled = true;
        cbstatus.Enabled = true;
        torderdate.Enabled = true;
        tordertime.Enabled = true;
        county.Enabled = true;
        appshe.Enabled = true;
        tfee.Enabled = true;
        paid.Enabled = true;
        asisValue.Enabled = true;
        repair.Enabled = true;
        efectivedate.Enabled = true;
        cbfailed.Enabled = true;
        cbreason.Enabled = true;
        cbagentreassign.Enabled = true;
        tpstnum.Enabled = true;
        tpstadd.Enabled = true;
        tpcity.Enabled = true;
        cbOPState.Enabled = true;
        tpzip.Enabled = true;
        duetimeampm.Enabled = true;
        saveclosephoto.Visible = true;
        savesubmit.Visible = true;
        PsfFee.Enabled = true;
        PsfPaid.Enabled = true;
        PsfCheck.Enabled = true;



        

    }
    //guardar FAIL
    protected void ImageButton5_Click(object sender, ImageClickEventArgs e)
    {

        int failid = int.Parse(cbreason.SelectedValue);
        string agent = cbagentreassign.Text;
        user = (rUser)Session["userid"];
        string responsable = user.getAlias();
        int respuesta = DB.addFail(orden, failid, agent, responsable);
        if (respuesta==1){

            DataSet dsf = DB.getFail(orden);
            if (dsf != null)
            {
                gv_fail.DataSource = dsf;
                gv_fail.DataBind();
                cbfailed.SelectedIndex = 0;
                cbreason.Enabled = false;
            }

        }else{
           
        }
    }



    protected void dateupload_TextChanged(object sender, EventArgs e)
    {

    }
   
    protected void ImageButton6_Click(object sender, ImageClickEventArgs e)
    {

        if (productlist.SelectedIndex == 0) { TableSize++; addnewcell(TableSize, jobtype.Text, -1); }
        else { TableSize++; addnewcell(TableSize, jobtype.Text, productlist.SelectedIndex); }
       
        
    }

    protected void upload_Click(object sender, ImageClickEventArgs e)
    {

        for (int i = 1; i <= TableSize ; i++)
        {
            
             DropDownList combon= (DropDownList)tablephoto.FindControl("cbphoto" + i);
             string nameView=  combon.SelectedItem.ToString();
             string value = combon.SelectedIndex.ToString();

             int viewid = DB.getViewId(nameView);
            string comment= ((TextBox)tablephoto.FindControl("comments"+i)).Text;
            FileUpload file= ((FileUpload)tablephoto.FindControl("file"+i));
            CheckBox c = (CheckBox)tablephoto.FindControl("ch"+i);
            Image photo= (Image)tablephoto.FindControl("photo"+i);
           
            if (photo.ImageUrl.Equals("~/img/notphoto.png"))
            {
                if (file.HasFile != false)
                {
                    try
                    {
                        

                        string filepath = file.PostedFile.FileName;
                        string filenamedos= file.FileName;
                        photo.ImageUrl = filepath;
                        string filename = "image_"+DateTime.Now.Year.ToString()+DateTime.Now.Month.ToString()+DateTime.Now.Day.ToString()+"_"+DateTime.Now.Hour.ToString()+DateTime.Now.Minute.ToString()+DateTime.Now.Second.ToString()+DateTime.Now.Millisecond.ToString()+"_"+filenamedos;
                        file.PostedFile.SaveAs(Server.MapPath("~\\temp\\" + filename));
                        photo.ImageUrl = "~\\temp\\" + filename;
                        photo.Width = 250;
                        photorb[i-1] = new RE_GenericBean();
                        photorb[i-1].strC1 = filename;//path
                        photorb[i-1].intC2 = viewid;//view
                        photorb[i-1].strC3 = comment;//comment
                        photorb[i-1].intC4 = 0; //indica que no viene de la basede datos
                        


                    }
                    catch (Exception ex)
                    {
                        

                    }
                } //hasfile
            }//haspicture Image
            if (i == 1) { ((Image)TabPanel2.FindControl("PhotoMain")).ImageUrl = photo.ImageUrl; }
                }
        email.Enabled = true;
            }


    protected void email_Click(object sender, ImageClickEventArgs e)
    {

        if (Utility.validarEmail(emailowner.Text))
        {
            string to = emailowner.Text;
            string from = "bpo@bpophotos.com";
            string subject = "BPO photos  "+tstnumber.Text+" "+tstaddress.Text+" "+tcity.Text+",  "+DB.getStateInitial(state.Text)+" "+tzip.Text;
            string body = "<h2>BPO photos  "+tstnumber.Text+" "+tstaddress.Text+" "+tcity.Text+",  "+DB.getStateInitial(state.Text)+" "+tzip.Text+"</h2>";
            string[] atach= new string[TableSize];
            for (int i=0; i< TableSize; i++){
                if (photorb[i+1]!=null){}
                 
                if (photorb[i+1]!=null)
                {
                    string strpath = photorb[i+1].strC1;
                     atach[i] = Server.MapPath(@"~\\temp\\"+photorb[i+1].strC1);
                     body = body + " ";
                
                }
                }
           
              Utility.sendMailAtach(from, to, subject, body, atach);
        }
        
        else{
             Response.Write("<" + "script language='javascript'>");
             Response.Write("alert('Please enter correct email address .');");
             Response.Write("<" + "/script>");
        
        }
    }


    public static TableCell newBox(int tam, string jobtype, int viewid)
    {//agrega nueva caja para subir photos



        TableCell result = new TableCell();

        Table table = new Table();

        TableRow newrow = new TableRow();

        TableCell newcell = new TableCell();

        newcell.Width = 250;

        newcell.HorizontalAlign = HorizontalAlign.Left;

        CheckBox check = new CheckBox();

        check.AutoPostBack = true;

        check.Height = 15;

        check.ID = "ch" + tam;

        newcell.Controls.Add(check);

        newrow.Cells.Add(newcell);

        table.Rows.Add(newrow);





        TableRow row2 = new TableRow();

        row2.Height = 150;

        TableCell newcell2 = new TableCell();

        newcell2.Width = 250;

        newcell2.BackColor = System.Drawing.Color.White;

        ImageButton btnimagen = new ImageButton();

        btnimagen.ID = "photo" + tam;

        btnimagen.BorderWidth = 0;

        btnimagen.ImageUrl = "~/img/notphoto.png";

        btnimagen.Width = 250;

        btnimagen.Height = 188;

        newcell2.Controls.Add(btnimagen);

        row2.Cells.Add(newcell2);

        table.Rows.Add(row2);

        TableRow row3 = new TableRow();

        TableCell newcell3 = new TableCell();

        newcell3.Width = 250;

        DropDownList cbphoto = new DropDownList();

        cbphoto.ID = "cbphoto" + tam;

        cbphoto.Width = 250;

        int product_id = DB.getProductId(jobtype);

        DataSet dsv = DB.getProductView(product_id);



        for (int j = 0; j < dsv.Tables[0].Rows.Count; j++)
        {

            ListItem item = new ListItem();

            item.Text = dsv.Tables[0].Rows[j][0].ToString();

            string valor = dsv.Tables[0].Rows[j][1].ToString();

            item.Value = valor;

            cbphoto.Items.Add(item);

        }

        //cbphoto.AutoPostBack = true;

        if (viewid == -1)
        {

            if (tam > dsv.Tables[0].Rows.Count)
            {

                int newindex = tam - dsv.Tables[0].Rows.Count;

                cbphoto.SelectedValue = dsv.Tables[0].Rows[0][2].ToString();



            }

            else
            {

                cbphoto.SelectedValue = (tam).ToString();



            }

        }

        else
        {

            cbphoto.SelectedValue = (viewid).ToString();

        }



        newcell3.Controls.Add(cbphoto);

        row3.Cells.Add(newcell3);

        table.Rows.Add(row3);



        TableRow row4 = new TableRow();

        TableCell newcell4 = new TableCell();

        newcell4.Width = 250;

        newcell4.Height = 45;

        FileUpload file = new FileUpload();

        file.ID = "file" + tam;

        file.Width = 250;

        file.Height = 25;

        file.EnableViewState = true;



        newcell4.Controls.Add(file);

        row4.Cells.Add(newcell4);

        table.Rows.Add(row4);



        TableRow row5 = new TableRow();

        TableCell newcell5 = new TableCell();

        newcell5.Width = 250;

        TextBox txt = new TextBox();

        txt.ID = "comments" + tam;

        txt.Width = 250;

        txt.Height = 50;

        txt.TextMode = TextBoxMode.MultiLine;

        txt.CssClass = "txtForm";

        newcell5.Controls.Add(txt);

        row5.Cells.Add(newcell5);

        table.Rows.Add(row5);

        result.Controls.Add(table);

        return result;

    }





    public static TableCell oldBox(int tam, string jobtype, int viewid, string image, string comments)
    {//agrega nueva caja para subir photos



        TableCell result = new TableCell();

        Table table = new Table();

        TableRow newrow = new TableRow();

        TableCell newcell = new TableCell();

        newcell.Width = 250;

        newcell.HorizontalAlign = HorizontalAlign.Left;

        CheckBox check = new CheckBox();

        check.AutoPostBack = true;

        check.Height = 15;

        check.ID = "ch" + tam;

        newcell.Controls.Add(check);

        newrow.Cells.Add(newcell);

        table.Rows.Add(newrow);



        //imagen 

        TableRow row2 = new TableRow();

        row2.Height = 188;

        TableCell newcell2 = new TableCell();

        newcell2.Width = 250;



        newcell2.BackColor = System.Drawing.Color.White;

        ImageButton btnimagen = new ImageButton();

        btnimagen.ID = "photo" + tam;

        btnimagen.BorderWidth = 0;

        if (!image.Equals(""))
        {

            btnimagen.ImageUrl = "~/data/photos/" + image;

        }

        else
        {

            btnimagen.ImageUrl = "~/img/notphoto.png";

        }

        btnimagen.Width = 250;

        btnimagen.Height = 188;





        //combobox

        newcell2.Controls.Add(btnimagen);

        row2.Cells.Add(newcell2);

        table.Rows.Add(row2);





        TableRow row3 = new TableRow();

        TableCell newcell3 = new TableCell();

        newcell3.Width = 250;

        DropDownList cbphoto = new DropDownList();

        cbphoto.ID = "cbphoto" + tam;

        cbphoto.Width = 250;

        int product_id = DB.getProductId(jobtype);

        DataSet dsv = DB.getProductView(product_id);



        for (int j = 0; j < dsv.Tables[0].Rows.Count; j++)
        {

            ListItem item = new ListItem();

            item.Text = dsv.Tables[0].Rows[j][0].ToString();

            string valor = dsv.Tables[0].Rows[j][1].ToString();

            item.Value = valor;

            cbphoto.Items.Add(item);



        }



        if (viewid == -1)
        {

            if (tam > dsv.Tables[0].Rows.Count)
            {

                int newindex = tam - dsv.Tables[0].Rows.Count;

                cbphoto.SelectedValue = dsv.Tables[0].Rows[0][2].ToString();



            }

            else
            {

                cbphoto.SelectedValue = (tam).ToString();



            }

        }

        else
        {

            cbphoto.SelectedValue = (viewid).ToString();

        }



        newcell3.Controls.Add(cbphoto);

        row3.Cells.Add(newcell3);

        table.Rows.Add(row3);





        //FileUpload

        TableRow row4 = new TableRow();

        TableCell newcell4 = new TableCell();

        newcell4.Width = 250;

        newcell4.Height = 50;

        FileUpload file = new FileUpload();

        file.ID = "file" + tam;

        file.Width = 250;

        file.Height = 25;

        file.EnableViewState = true;

        file.Enabled = false;

        newcell4.Controls.Add(file);

        row4.Cells.Add(newcell4);

        table.Rows.Add(row4);





        //comments

        TableRow row5 = new TableRow();

        TableCell newcell5 = new TableCell();

        newcell5.Width = 250;

        TextBox txt = new TextBox();

        txt.ID = "comments" + tam;

        txt.Text = comments;

        txt.Width = 250;

        txt.TextMode = TextBoxMode.MultiLine;

        txt.CssClass = "txtForm";

        txt.Height = 50;

        newcell5.Controls.Add(txt);

        row5.Cells.Add(newcell5);

        table.Rows.Add(row5);

        result.Controls.Add(table);

        return result;

    }

 



    protected void saveclosephoto_Click(object sender, ImageClickEventArgs e)
    {
        
       
        for (int i = 0; i < TableSize+1; i++ ) {
            int imas = i + 1;
            DropDownList combon = (DropDownList)tablephoto.FindControl("cbphoto" + imas);
           
            if ( combon!=null){ 
                if (photorb[i]!=null){
                    string nameView = combon.SelectedItem.ToString();
                    string value = combon.SelectedIndex.ToString();
                    if (!nameView.ToUpper().Equals(photorb[i].intC2)){
                        //actualiza
                        int viewid = DB.getViewId(nameView);
                      //  DB.updatePhoto(orden, );
                       
                    }
                    string comment = ((TextBox)tablephoto.FindControl("comments" + imas)).Text;
                    
                
                }
                
            }

         

            if(photorb[i]!=null){
            if (photorb[i].intC4!=1){
            int res1= DB.addPhoto(orden, photorb[i].intC2, photorb[i].strC3, photorb[i].strC1);
            if(res1==1){
                int res2 = DB.moveImage(photorb[i].strC1);
            }
            }

            }
        
        }//despues for

        int campoid = DB.getCampoID("PHOTOS", "UPLOADBY");
        int res3 = DB.savePhotosUploadby(orden, campoid, cbuploadby.SelectedValue);

        int intCampo = DB.getCampoID("PHOTOS", "RECEIVED");
        int cvendor = DB.saveOrderProcess(orden, intCampo, photosreceived.Text);

        int campoid2 = DB.getCampoID("PHOTOS", "COMPLETEDSET");
        int res4 = DB.saveValueCampoComboBox(orden, campoid2, completeset.Text);

        int campoid3 = DB.getCampoID("PHOTOS", "EXTERIORONLY");
        int res5 = DB.saveValueCampoComboBox(orden, campoid3, typeonly.Text);

        int campoid4 = DB.getCampoID("PHOTOS", "COMMENTS");
        int res6 = DB.saveValueCampo(orden, campoid4, commnetsphotos.Text);
       
        Response.Redirect("WorkSpace.aspx");
    }
    protected void ImageButton7_Click(object sender, ImageClickEventArgs e)
    {
        cbuploadby.Enabled = true;
        dateupload.Enabled = true;
        timeupload.Enabled = true;
        typeonly.Enabled = true;
        photosreceived.Enabled = true;
        completeset.Enabled = true;
        commnetsphotos.Enabled = true;

    }
    protected void Page_Unload(object sender, EventArgs e)
    {
        for (int i = 0; i < TableSize - 1; i++)
        {
            DropDownList combon = (DropDownList)tablephoto.FindControl("cbphoto" + i);
            if (combon != null) { combon.Dispose(); }
            TextBox txt = (TextBox)tablephoto.FindControl("comments" + i);
            if (txt != null) { txt.Dispose();}
            FileUpload file = ((FileUpload)tablephoto.FindControl("file" + i));
            if (file!=null){  file.Dispose();}
            CheckBox c = (CheckBox)tablephoto.FindControl("ch" + i);
            if (c != null){ c.Dispose();}
            Image photo = (Image)tablephoto.FindControl("photo" + i);
            if (photo!=null){ photo.Dispose();}
           

        }
        
      
        
    }

    private void fillaccounts(RE_GenericBean rg)
    {
        try
        {
            RE_GenericBean rgb = rg;
            string rxml = null;
            com.bpophotos.www.Service service = new com.bpophotos.www.Service();
            rxml = service.getAccounts();


            if (!rxml.Equals("") || rxml != null)
            {
                DataSet dsclient = Utility.getAccounts(rxml);
                ListItem listitem0 = new ListItem();
                listitem0.Text = "Select One"; listitem0.Value = "";
                account.Items.Add(listitem0);


                for (int ii = 0; ii <= (dsclient.Tables[0].Rows.Count - 1); ii++)
                {
                    ListItem listitem = new ListItem();
                    listitem.Text = dsclient.Tables[0].Rows[ii][1].ToString();
                    listitem.Value = dsclient.Tables[0].Rows[ii][0].ToString();
                    account.Items.Add(listitem);

                    if (dsclient.Tables[0].Rows[ii][0].ToString() == rgb.strC22.ToString())
                    {
                        account.SelectedValue = listitem.Value;
                    }
                }
            }


        }
        catch (Exception ee)
        {
            Utility.writeError("No devolvio Accounts WS getAccounts" + ee.Message);

        }
    }
    private void fillstatus(RE_GenericBean rg)
    {
        RE_GenericBean rgb2 = rg;

        DataSet  dss = DB.GetStatus();
        cbstatus.Items.Add("Select One");
        for (int i = 0; i <= (dss.Tables[0].Rows.Count - 1); i++)
        {

            ListItem listitem = new ListItem();
            listitem.Text = Utility.toCapital(dss.Tables[0].Rows[i][1].ToString());
            listitem.Value = dss.Tables[0].Rows[i][0].ToString();
            cbstatus.Items.Add(listitem);
            
            if (dss.Tables[0].Rows[i][1].ToString() == rgb2.strC10.ToString())
            {
                cbstatus.SelectedValue = listitem.Value;
            }
        }

    }

}

